﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using KandaAlpha.Domain.Model.Entities;
using KandaAlpha.Domain.Repository;
using System.Data.Objects;
using System.Data;
using System.Data.Objects.DataClasses;
using System.Linq.Expressions;
using System.Threading;
using System.Web;

namespace KandaAlpha.Infrastructure.Repository.EF
{

    /// <summary>
    /// Manages the lifecycle of the EF's object context
    /// </summary>
    /// <remarks>Uses a context per http request approach or one per thread in non web applications</remarks>
    public static class ObjectContextManager
    {
        #region Private Members

        // accessed via lock(_threadObjectContexts), only required for multi threaded non web applications
        private static readonly Hashtable _threadObjectContexts = new Hashtable();

        // key for storage in HttpContext
        private const string OBJECT_CONTEXT_KEY = "KandaAlpha.Infrastructure.Repository.EF.ObjectContext";
        
        #endregion

        /// <summary>
        /// Returns the active object context
        /// </summary>
        public static ObjectContext GetObjectContext()
        {
            ObjectContext objectContext = GetCurrentObjectContext();
            if (objectContext == null) // create and store the object context
            {
                objectContext = new KandaAlphaContext();
                StoreCurrentObjectContext(objectContext);
            }
            return objectContext;
        }

        /// <summary>
        /// Gets the repository context
        /// </summary>
        /// <returns>An object representing the repository context</returns>
        public static object GetRepositoryContext()
        {
            return GetObjectContext();
        }

        /// <summary>
        /// Sets the repository context
        /// </summary>
        /// <param name="repositoryContext">An object representing the repository context</param>
        public static void SetRepositoryContext(object repositoryContext)
        {
            if (repositoryContext == null)
            {
                RemoveCurrentObjectContext();
            }
            else if (repositoryContext is ObjectContext)
            {
                StoreCurrentObjectContext((ObjectContext)repositoryContext);
            }
        }


        #region Object Context Lifecycle Management

        /// <summary>
        /// gets the current object context 		
        /// </summary>
        private static ObjectContext GetCurrentObjectContext()
        {
            ObjectContext objectContext = null;
            if (HttpContext.Current == null)
                objectContext = GetCurrentThreadObjectContext();
            else
                objectContext = GetCurrentHttpContextObjectContext();
            return objectContext;
        }

        /// <summary>
        /// sets the current session 		
        /// </summary>
        private static void StoreCurrentObjectContext(ObjectContext objectContext)
        {
            if (HttpContext.Current == null)
                StoreCurrentThreadObjectContext(objectContext);
            else
                StoreCurrentHttpContextObjectContext(objectContext);
        }

        /// <summary>
        /// remove current object context 		
        /// </summary>
        private static void RemoveCurrentObjectContext()
        {
            if (HttpContext.Current == null)
                RemoveCurrentThreadObjectContext();
            else
                RemoveCurrentHttpContextObjectContext();
        }

        #region private methods - HttpContext related

        /// <summary>
        /// gets the object context for the current thread
        /// </summary>
        private static ObjectContext GetCurrentHttpContextObjectContext()
        {
            ObjectContext objectContext = null;
            if (HttpContext.Current.Items.Contains(BuildHttpContextName()))
                objectContext = (ObjectContext)HttpContext.Current.Items[BuildHttpContextName()];
            return objectContext;
        }

        private static void StoreCurrentHttpContextObjectContext(ObjectContext objectContext)
        {
            if (HttpContext.Current.Items.Contains(BuildHttpContextName()))
                HttpContext.Current.Items[BuildHttpContextName()] = objectContext;
            else
                HttpContext.Current.Items.Add(BuildHttpContextName(), objectContext);
        }

        /// <summary>
        /// remove the session for the currennt HttpContext
        /// </summary>
        private static void RemoveCurrentHttpContextObjectContext()
        {
            ObjectContext objectContext = GetCurrentHttpContextObjectContext();
            if (objectContext != null)
            {
                HttpContext.Current.Items.Remove(BuildHttpContextName());
                objectContext.Dispose();
            }
        }

        #endregion

        #region private methods - ThreadContext related

        /// <summary>
        /// gets the session for the current thread
        /// </summary>
        private static ObjectContext GetCurrentThreadObjectContext()
        {
            ObjectContext objectContext = null;
            Thread threadCurrent = Thread.CurrentThread;
            if (threadCurrent.Name == null)
                threadCurrent.Name = Guid.NewGuid().ToString();
            else
            {
                object threadObjectContext = null;
                lock (_threadObjectContexts.SyncRoot)
                {
                    threadObjectContext = _threadObjectContexts[BuildContextThreadName()];
                }
                if (threadObjectContext != null)
                    objectContext = (ObjectContext)threadObjectContext;
            }
            return objectContext;
        }

        private static void StoreCurrentThreadObjectContext(ObjectContext objectContext)
        {
            lock (_threadObjectContexts.SyncRoot)
            {
                if (_threadObjectContexts.Contains(BuildContextThreadName()))
                    _threadObjectContexts[BuildContextThreadName()] = objectContext;
                else
                    _threadObjectContexts.Add(BuildContextThreadName(), objectContext);
            }
        }

        private static void RemoveCurrentThreadObjectContext()
        {
            lock (_threadObjectContexts.SyncRoot)
            {
                if (_threadObjectContexts.Contains(BuildContextThreadName()))
                {
                    ObjectContext objectContext = (ObjectContext)_threadObjectContexts[BuildContextThreadName()];
                    if (objectContext != null)
                    {
                        objectContext.Dispose();
                    }
                    _threadObjectContexts.Remove(BuildContextThreadName());
                }
            }
        }

        private static string BuildContextThreadName()
        {
            return Thread.CurrentThread.Name;
        }

        private static string BuildHttpContextName()
        {
            return OBJECT_CONTEXT_KEY;
        }

        #endregion

        #endregion


    }
}
